package com.app.micaihu.view.login.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.TypeConstant
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.view.login.contract.LogInContract
import com.app.micaihu.view.login.presenter.LogInPresenter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ToastUtils
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.login_forget_password_confirm_activity.*
import java.util.concurrent.TimeUnit

/**
 * Created by linkai on 2017/7/04.
 * 忘记密码 确认界面
 */
class ForgetPasswordConfirmActivity : BaseMvpActivity<LogInContract.View, LogInPresenter>(), LogInContract.View {
    override fun getPresenter() = LogInPresenter()

    override fun getLayoutId() = R.layout.login_forget_password_confirm_activity

    override fun getBundle(bundle: Bundle) {
        phone = bundle.getString(Config.Extra.phone, "")
    }

    var phone: String = ""
    private var phoneText: String = ""
    private var isShowPassWord1 = false
    private var isShowPassWord2 = false
    private var mdDisposable: Disposable? = null


    var textWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable) {
            tvOk.isEnabled = etPassWord1.text.toString().isNotEmpty() && etPassWord2.text.toString().isNotEmpty()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun setData() {
        phoneText = if (phone.length == 11) {
            mPresenter?.sendCode(phone, TypeConstant.FINDPWD_CODE)
            phone.replaceRange(3, 7, "****")
        } else {
            phone
        }
        tvDesc.text = "账号已与${phoneText}绑定\n请输入验证码，确认身份"
    }

    override fun addListeners() {
        tvCode.setOnClickListener {
            mPresenter?.sendCode(phone, TypeConstant.FINDPWD_CODE)
        }
        tvOk.setOnClickListener {
            if (etCode.text.toString().isEmpty()) {
                ToastUtils.showShort("请输入验证码")
            } else {
                if (etPassWord1.text.toString() == etPassWord2.text.toString()) {
                    mPresenter?.changePassword(phone, etCode.text.toString(), etPassWord1.text.toString(), TypeConstant.CHANGE_PWD_TYPE2)
                } else {
                    ToastUtils.showShort("密码不一致")
                }
            }
        }
        ivPassWord1.setOnClickListener {
            if (isShowPassWord1) {
                //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                etPassWord1.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                ivPassWord1.setImageResource(R.mipmap.login_password_hint)
            } else {
                //选择状态 显示明文--设置为可见的密码
                etPassWord1.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                ivPassWord1.setImageResource(R.mipmap.login_password_show)
            }
            etPassWord1.setSelection(etPassWord1.text.toString().length)
            isShowPassWord1 = !isShowPassWord1
        }
        ivPassWord2.setOnClickListener {
            if (isShowPassWord2) {
                //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                etPassWord2.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                ivPassWord2.setImageResource(R.mipmap.login_password_hint)
            } else {
                //选择状态 显示明文--设置为可见的密码
                etPassWord2.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                ivPassWord2.setImageResource(R.mipmap.login_password_show)
            }
            etPassWord2.setSelection(etPassWord2.text.toString().length)
            isShowPassWord2 = !isShowPassWord2
        }
        etPassWord1.addTextChangedListener(textWatcher)
        etPassWord2.addTextChangedListener(textWatcher)
    }

    @SuppressLint("SetTextI18n", "AutoDispose")
    private fun startTimer() {
        val count = 60
        mdDisposable?.dispose()
        //从1开始发射60个数字为：0-60依次输出，延时0s执行，每1s发射一次。
        mdDisposable = Flowable.intervalRange(1, count.toLong(), 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext { aLong: Long ->
                    tvCode.isEnabled = false
                    tvCode.setTextColor(ColorUtils.getColor(R.color.color999))
                    tvCode.text = (count - aLong).toString() + "s后重新获取"
                }.doOnComplete {
                    //倒计时完毕置为可点击状态
                    tvCode.isEnabled = true
                    tvCode.setTextColor(ColorUtils.getColor(R.color.app_theme))
                    tvCode.text = "获取验证码"
                }.subscribe()
    }

    override fun handleSendCode(result: BaseBean<Any?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
            tvCode.isEnabled = true
            tvCode.setTextColor(ColorUtils.getColor(R.color.app_theme))
            tvCode.text = "获取验证码"
        } else {
            if (result.isSuccess()) {
                ToastUtils.showShort("验证码已发送成功，请注意查收")
                startTimer()
            } else {
                tvCode.isEnabled = true
                tvCode.setTextColor(ColorUtils.getColor(R.color.app_theme))
                tvCode.text = "获取验证码"
                ToastUtils.showShort(result.msg)
            }
        }

    }

    override fun handleChangePassword(result: BaseBean<Any?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (result.isSuccess()) {
                UserInforManager.getInstance().userInfor?.let {
                    it.password = etPassWord1.text.toString()
                    //保存到本地
                    UserInforManager.getInstance().saveUserInfor(it)
                }
                ActivityUtils.finishActivity(ForgetPasswordActivity::class.java)
                ActivityUtils.finishActivity(ForgetPasswordConfirmActivity::class.java)
            }
            ToastUtils.showShort(result.msg)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mdDisposable?.dispose()
    }
}